package com.version1_3.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.util.httpRequest.HttpRequest;
import com.version1_2.controller.UserController1_2;
import com.version1_3.service.UserSerivce1_3;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * Created by kuibu on 15/12/25.
 */

@Controller
public class UserController1_3 {
    private static final Logger LOGGER = Logger.getLogger(UserController1_3.class);

    @Autowired
    private UserSerivce1_3 userService13;

    @Autowired
    private UserController1_2 userController12; // 1.2版本接口使用service层

    /*
    * 更新接口内容
    * 1. 登陆用户获取一级分类信息;
    * 2. 登陆用户在主界面上对三级分类进行排序置顶;
    * */

    /**
     * 调用接口: http://139.129.18.232:7080/kuibuversion1/version1_3/user/sortSecondType/{userId}/{firstType}
     * <p>
     *
     * @warnning: 登陆用户更新某一个一级分类的关注信息 - 目前iOS只用了SubscriController的changeUserFocus接口
     */
    @RequestMapping(value = "/version1_3/user/sortSecondType/{userId}/{firstType}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String updateFirstFocus(@RequestBody JSONObject jsonObject, @PathVariable("firstType") int firstType, @PathVariable("userId") int userId) {

        JSONArray firstFocusJsonArray = jsonObject.getJSONArray("firstTypeFocusStr");

        if (firstFocusJsonArray == null) {
            LOGGER.error("登陆用户对主界面二级分类进行置顶,未获取到客户端发送参数");
            return "{\"code\":500}";
        } else {
            return userService13.updateFirstFocus(firstFocusJsonArray, firstType, userId);
        }
    }

    /**
     * 调用接口: http://139.129.18.232:7080/kuibuversion1/version1_3/user/topThirdType
     * <p>
     * 登陆用户在主界面上对三级分类进行排序置顶
     */
    @RequestMapping(value = "/version1_3/user/topThirdType", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String topThirdType(@RequestBody JSONObject jsonObject) {

        try {
            int userId = jsonObject.getIntValue("userId");
            int firstType = jsonObject.getInteger("firstType");
            int thirdType = jsonObject.getIntValue("thirdType");

            return userService13.topThirdType(thirdType, firstType, userId);
        } catch (Exception excetpion) {
            LOGGER.error("客户端发送数据格式错误,topThridTypeJsonString: " + jsonObject.toJSONString());
            return "{\"code\":500}";
        }
    }

    /**
     * 调用接口: http://139.129.18.232:7080/kuibuversion1/version1_3/user/removeTopThirdType
     * <p>
     * 登陆用户在主界面上取消排序置顶
     */
    @RequestMapping(value = "/version1_3/user/removeTopThirdType", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String removeTopThirdType(@RequestBody JSONObject jsonObject) {

        try {
            int userId = jsonObject.getIntValue("userId");
            int firstType = jsonObject.getInteger("firstType");
            int thirdType = jsonObject.getIntValue("thirdType");

            return userService13.removeTopThirdType(thirdType, firstType, userId);
        } catch (Exception excetpion) {
            LOGGER.error("取消置顶错误", excetpion);
            return "{\"code\":500}";
        }
    }


    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/updateFocusList/{userId}
     *
     * @Description: 更新关注列表 - 目前iOS只用了SubscriController的changeUserFocus接口
     */
    @RequestMapping(value = "/version1_3/user/updateFocusList/{userId}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String updateFocusList(@RequestBody JSONObject jsonObject, @PathVariable("userId") int userId) {

        if (jsonObject == null) {
            LOGGER.error("更新用户列表,未获取到客户端发送参数");
            return "{\"code\":500}";
        } else {
            return userService13.updateFocusList(jsonObject.getJSONArray("userFocusList"), userId);
        }
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/login
     *
     * @Description: 用户登陆
     */
    @RequestMapping(value = "/version1_3/user/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String login(@RequestBody JSONObject jsonObject) {
        try {
            String baiduId = "";
            if (jsonObject.getString("baiduId") != null) {
                baiduId = jsonObject.getString("baiduId");
            }
            return userService13.login(
                    jsonObject.getIntValue("userId"),
                    jsonObject.getString("telnumber"),
                    jsonObject.getString("password"), baiduId);
        } catch (Exception exception) {
            LOGGER.error("用户登陆version1.3出错", exception);
            return "{\"code\":500}";
        }
    }

    /**
     * 调用接口:http://139.129.18.232:7080/kuibuversion1/version1_3/user/searchSchool/{schoolKey}
     *
     * @Description: 搜索学校
     */
    @RequestMapping(value = "/version1_3/user/searchSchool/{schoolKey}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String searchSchool(@PathVariable("schoolKey") String schoolKey) {
        return userService13.searchSchool(schoolKey);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/register/{telnumber}/{password}/{inviteCode}
     *
     * @Description: 用户注册, 使用邀请码
     */
    @RequestMapping(value = "/version1_3/user/register/{telnumber}/{password:.+}/{inviteCode}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String registerwithInviteCode(@PathVariable("telnumber") String telnumber, @PathVariable("password") String password, @PathVariable("inviteCode") String inviteCode)
            throws UnsupportedEncodingException {
        return userService13.registerWithInviteCode(telnumber, password, inviteCode);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/register/{telnumber}/{password}/{inviteCode}
     *
     * @Description: 用户网页注册
     */
    @RequestMapping(value = "/user/htmlRegister/{telnumber}/{password:.+}/{inviteCode}", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ModelAndView htmlRegister(@PathVariable("telnumber") String telnumber, @PathVariable("password") String password, @PathVariable("inviteCode") String inviteCode)
            throws UnsupportedEncodingException {
        String userInviteCode = userService13.htmlRegister(telnumber, password, inviteCode);
        ModelAndView modelAndView = null;

        if (!userInviteCode.contains("false")) {
            JSONObject jsonObject = JSON.parseObject(userInviteCode);
            modelAndView = new ModelAndView("/guanwang/htmlRegisterSuccess");
            modelAndView.addObject("inviteCode", jsonObject.get("inviteCode"));
        } else {
            modelAndView = new ModelAndView("/guanwang/htmlRegisterSuccess");
        }

        return modelAndView;
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/htmlLogin/{telnumber}/{password}
     *
     * @Description: 用户网页登陆
     */
    @RequestMapping(value = "/user/htmlLogin/{telnumber}/{password}", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public ModelAndView htmlLogin(@PathVariable("telnumber") String telnumber, @PathVariable("password") String password)
            throws UnsupportedEncodingException {
        ModelAndView modelAndView = new ModelAndView("/guanwang/htmlLoginPage");
        return modelAndView;
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/htmlGetInviteCode/{telnumber}/{password}
     *
     * @Description: 网页端获取用户邀请码
     */
    @RequestMapping(value = "/user/htmlGetInviteCode/{telnumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String htmlGetInviteCode(@PathVariable("telnumber") String telnumber) {
        return userService13.getInviteCode(telnumber);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/getHtmlConfirmCode/{telnumber}
     *
     * @Description: 获取手机验证码
     */
    @RequestMapping(value = "/user/getHtmlConfirmCode/{telnumber}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getConfirmCode(@PathVariable("telnumber") String telnumber) {
        String urlPrefix = "http://hprpt2.eucp.b2m.cn:8080/sdkproxy/sendsms.action?cdkey=8SDK-EMY-6699-RFUOO&password=228007&phone=";
        String urlMid = "&message=";
        String urlPostfix = "为您的验证码,欢迎使用跬步App,跬步,陪你走好大学的每一步!";

        int confirmCode = new Random().nextInt(9999) % (9000) + 1000;

        HttpRequest.sendGet(urlPrefix + telnumber + urlMid + confirmCode + urlPostfix);
        return "{\"confirmCode\":" + confirmCode + "}";
    }


    /**
     * 调用接口: http://139.129.18.232:7080/kuibuversion1/user/thirdPart/register/{platform}/{openid}/{token}
     *
     * @description: 第三方平台注册或是刷新token - iOS版本,加入uuid
     */
    @RequestMapping(value = "/user/thirdPart/register/{platform}/{openid}/{token:.+}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String thirdPartRegister(@RequestBody JSONObject jsonObject, @PathVariable("platform") String platform, @PathVariable("openid") String openid, @PathVariable("token") String token) {
        String uuid = "";
        String baiduId = "";

        if (jsonObject.getString("uuid") != null) {
            // 如果有手机的uuid数据
            uuid = jsonObject.getString("uuid");
        }

        if (jsonObject.getString("baiduId") != null) {
            baiduId = jsonObject.getString("baiduId");
        }
        return userService13.thirdPartRegister(platform, openid, token, uuid, baiduId);
    }


    /**
     * TODO: 调用接口: http://139.129.18.232:7080/kuibuversion1/version1_2/user/thirdPart/register/{platform}/{openid}/{token}
     *
     * @description: 第三方平台注册或是刷新token - Android版本,加入uuid
     */
    @RequestMapping(value = "/version1_2/user/thirdPart/register/{platform}/{openid}/{token:.+}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String thirdPartRegisterAndroid(@RequestBody JSONObject jsonObject, @PathVariable("platform") String platform, @PathVariable("openid") String openid, @PathVariable("token") String token) {
        String uuid = "";
        String baiduId = "";

        if (jsonObject.getString("uuid") != null) {
            // 如果有手机的uuid数据
            uuid = jsonObject.getString("uuid");
        }

        if (jsonObject.getString("baiduId") != null) {
            baiduId = jsonObject.getString("baiduId");
        }
        return userService13.thirdPartRegisterAndroid(platform, openid, token, uuid, baiduId);
    }


    /**
     * TODO: 调用接口: http://139.129.18.232:7080/kuibuversion1/user/thirdPart/login/{openid}
     *
     * @descripton: 第三方登陆 iOS版本
     */
    @RequestMapping(value = "/user/thirdPart/login/{openid}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String thirdPartLogin(@PathVariable("openid") String openid, @RequestBody JSONObject jsonObject) {
        String baiduId = "";
        try {
            baiduId = jsonObject.getString("baiduId");
        } catch (Exception e) {
            LOGGER.info("No baiduId Exist");
        }
        return userService13.thirdPartLogin(openid, "iOS", baiduId);
    }

    /**
     * TODO: 调用接口: http://139.129.18.232:7080/kuibuversion1/version1_2/user/thirdPart/login/{openid}
     *
     * @descripton: 第三方登陆 - Android版本
     */
    @RequestMapping(value = "/version1_2/user/thirdPart/login/{openid}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String thirdPartLoginAndroid(@PathVariable("openid") String openid, @RequestBody JSONObject jsonObject) {
        String baiduId = "";
        try {
            baiduId = jsonObject.getString("baiduId");
        } catch (Exception e) {
            LOGGER.info("No baiduId Exist");
        }
        return userService13.thirdPartLogin(openid, "Android", baiduId);
    }


    /**
     * 调用接口: http://139.129.18.232/kuibuversion1/user/registerSchoolNeeded/{telnumber}/{password}
     *
     * @descripiton: 用户注册, 必须填写学校信息,加入uuid
     */
    @RequestMapping(value = "/user/registerSchoolNeeded/{telnumber}/{password:.+}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String register(@PathVariable("telnumber") String telnumber, @PathVariable("password") String password, @RequestBody JSONObject jsonObject) {
        String inviteCode = "";
        String school = "";
        String uuid = "";

        try {
            inviteCode = jsonObject.getString("inviteCode");
            school = jsonObject.getString("school");

            if (jsonObject.getString("uuid") != null) {
                // 如果发送手机uuid
                uuid = jsonObject.getString("uuid");
            }

            return userService13.registerSchoolNeeded(telnumber, password, inviteCode, school, uuid);
        } catch (Exception exception) {
            LOGGER.error("jsonObject: " + jsonObject.toJSONString() + " ,telnumber: " + telnumber + " ,password: " + password, exception);
            return "{\"error\"}";
        }
    }


    /**
     * 调用接口: http://139.129.18.232:7080/kuibuversion1/user/accumulate/{userId}
     *
     * @Description: 日积跬步
     * 增加缓存清除功能 3.25
     */
    @RequestMapping(value = "/user/accumulate/{userId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String accumulatePage(HttpServletRequest request, @PathVariable("userId") int userId) {

        boolean cleanCache = false;
        if (request.getParameter("cleanCache") != null) {
            cleanCache = Boolean.parseBoolean((String) request.getParameter("cleanCache"));
        }
        return userService13.getAccumulatePage(userId, cleanCache);
    }


    /*-------------------------------------------- version1.2接口 ------------------------------------------------------*/

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/register/{telnumber}/{password}
     *
     * @Description: 用户注册
     */
    @RequestMapping(value = "/version1_3/user/register/{telnumber}/{password:.+}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String register(@PathVariable("telnumber") String telnumber, @PathVariable("password") String password)
            throws UnsupportedEncodingException {
        return userController12.register(telnumber, password);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/message/{userId}
     *
     * @Description: 检查是否有消息
     */
    @RequestMapping(value = "/version1_3/user/message/{userId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String hasMessage(@PathVariable("userId") int userId) {
        return userController12.hasMessage(userId);
    }


    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/message/reply/{userId}/{pageNumber}
     *
     * @Description: 获取用户回复列表信息
     */
    @RequestMapping(value = "/version1_3/user/message/reply/{userId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getReplyMessage(@PathVariable("userId") int userId,
                                  @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        return userController12.getReplyMessage(userId, pageNumber);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/message/praise/{userId}/{pageNumber}
     *
     * @Description: 获取用户点赞列表信息
     */
    @RequestMapping(value = "/version1_3/user/message/praise/{userId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getPraiseMessage(@PathVariable("userId") int userId,
                                   @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        return userController12.getPraiseMessage(userId, pageNumber);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/message/system/{userId}
     *
     * @Description: 获取用户系统消息, 正在写，需要设计方面给出设计。。。
     */
    @RequestMapping(value = "/version1_3/user/message/system/{userId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getSystemMessage(@PathVariable("userId") int userId)
            throws UnsupportedEncodingException {
        return userController12.getSystemMessage(userId);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/getCollectList/{userId}/{pageNumber}
     *
     * @Description: 登录用户得到收藏列表
     */
    @RequestMapping(value = "/version1_3/user/getCollectList/{userId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getCollectList(@PathVariable("userId") int userId, @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        return userController12.getCollectList(userId, pageNumber);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/getSecondTypeCollectList/{userId}/{secondType}/{pageNumber}
     *
     * @Description: 根据二级分类ID获取用户收藏中特定的二级分类的文章
     */
    @RequestMapping(value = "/version1_3/user/getSecondTypeCollectList/{userId}/{secondType}/{pageNumber}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getSecondTypeCollectList(@PathVariable("userId") int userId, @PathVariable("secondType") int secondType, @PathVariable("pageNumber") int pageNumber) throws UnsupportedEncodingException {
        return userController12.getSecondTypeCollectList(userId, secondType, pageNumber);
    }


    /**
     * 调用接口: http://139.129.18.232:7080/kuibuversion1/user/checkRegister/{registerInfo}
     *
     * @Description: 验证用户邮箱或手机号已经被注册
     */
    @RequestMapping(value = "/version1_3/user/checkRegister/{registerInfo}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkRegister(@PathVariable("registerInfo") String registerInfo) {
        return userController12.checkRegister(registerInfo);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/user/forgetPass/{telnumber}/{newPassword}
     *
     * @description: 忘记密码
     */
    @RequestMapping(value = "/version1_3/user/forgetPass/{telnumber}/{newPassword:.+}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String forgetPass(@PathVariable("telnumber") String telnumber, @PathVariable("newPassword") String newPassword) {
        return userController12.forgetPass(telnumber, newPassword);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/changePasswd
     *
     * @Description: 登陆用户更改密码
     */
    @RequestMapping(value = "/version1_3/user/changePasswd", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String changePasswd(HttpServletRequest request, @RequestBody JSONObject jsonObject)
            throws UnsupportedEncodingException {
        return userController12.changePasswd(request, jsonObject);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/updateInfo
     *
     * @Description: 更改用户个人信息
     */
    @RequestMapping(value = "/version1_3/user/updateInfo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String updateInfo(HttpServletRequest request, @RequestBody JSONObject jsonObject)
            throws UnsupportedEncodingException {
        return userController12.updateInfo(request, jsonObject);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/feedback
     *
     * @Description: 用户反馈
     */
    @RequestMapping(value = "/version1_3/user/feedback", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String feedback(HttpServletRequest request, @RequestBody JSONObject jsonObject)
            throws UnsupportedEncodingException {
        return userController12.feedback(request, jsonObject);
    }

    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/doCollect
     *
     * @Description: 记录、删除用户单次收藏,增加积分记录
     */
    @RequestMapping(value = "/version1_3/user/doCollect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String doCollect(HttpServletRequest request, @RequestBody JSONObject jsonObject)
            throws UnsupportedEncodingException {
        return userController12.doCollect(request, jsonObject);
    }


    /**
     * 调用接口：http://139.129.18.232:7080/kuibuversion1/version1_3/user/delCollect
     *
     * @Description: 删除用户收藏
     */
    @RequestMapping(value = "/version1_3/user/delCollect", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String delCollect(HttpServletRequest request, @RequestBody JSONObject jsonObject)
            throws UnsupportedEncodingException {
        return userController12.delCollect(request, jsonObject);
    }


}
